#!/bin/bash
# collect_sysinfo.sh
# 一键收集系统诊断信息

OUTFILE="sysinfo_$(date '+%Y-%m-%d-%H:%M:%S').log"

{
echo "================= 基本信息 ================="
echo "硬件型号: $HARDWARE，这是公司产品的硬件型号环境变量，可能为空"
echo "当前时间: $(date "+%Y-%m-%d %H:%M:%S")"
echo "系统运行时间: $(uptime -p)"
echo "系统启动时间: $(uptime -s)"
echo "系统版本: $(cat /etc/*release | head -n 1)"
echo "内核版本: $(uname -r)"
echo "完整内核信息: $(uname -a)"

echo
echo "================= 硬盘使用情况 ================="
df -hT

echo
echo "================= 网络信息 ================="
ip addr show
echo
echo "---- 路由表 ----"
ip route
echo
echo "---- 当前监听端口 ----"
ss -tulwn
echo "---- 连接数量统计 ----"
ss -s

echo
echo "================= 内核日志 (dmesg) ================="
echo "---- 内核报错/警告 ----"
dmesg -T --level=err,warn,crit,alert,emerg | tail -n 50

echo
echo "---- 关键关键词匹配 ----"
dmesg -T | egrep -i "error|fail|warn|critical|panic|segfault|timeout" | tail -n 50

echo
echo "================= 系统日志 (/var/log/messages) ================="
if [ -f /var/log/messages ]; then
    tail -n 50 /var/log/messages
elif [ -f /var/log/syslog ]; then
    tail -n 50 /var/log/syslog
else
    echo "未找到系统日志文件"
fi

echo
echo "================= 用户登录情况 ================="
w
last -n 5

} | tee "$OUTFILE"

echo
echo "✅ 信息已收集到文件: $OUTFILE"
